<?php

	/**
	 * Defines a class to be used for Time Data Typing with PHP
	 * 
	 * @author Pablo Santiago Sánchez <phackwer@gmail.com>
	 * @copyright Copyright (c) 2008, Pablo Santiago Sánchez
	 * @license http://opensource.org/licenses/bsd-license.php BSD License
	 * @package pop
	 * @subpackage datatypes
	 */

	/**
	 * Class used to handle time.
	 * Only HH:MM:SS format allowed.
	 * 
	 * @package pop
	 * @subpackage datatypes
	 */
	class PTime extends PTypeBase
	{
		/**
		 * Constructor, in which you must inform the default time.
		 * If none is informed, it uses TIME as default
		 * @param string $defaultval Default value. Must be a valid time
		 */
		public function __construct($defaultval = TIME)
		{
			$this->__set("value", $defaultval);
			$this->defaultval 	= $defaultval;
		}

		/**
		 * Magic method used to set the value and check if it's valid
		 * @param string $name name of the value
		 * @param string $value value itself
		 * @return bool 
		 */
		public function __set($name, $value)
		{
			if ($value === "")
				$value = null;

			if(strstr($value, " "))
			{
				$value = explode(" ",$value);
				$value = $value[1];
			}

			$time = explode(":",$value);

			//filter time, because on MSSQL it may come with miliseconds
			if ($time[2] && strstr($time[2], "."))
			{
				$time[2] = substr($time[2],0,2);
				$value = substr($value, 0, strpos($value, "."));
			}

			if ($name != "value")
			{
				throw new Exception("This attribute cannot be set");
			}
			else if ((!is_null($this->defaultval) && !is_null($value)) && !ctype_digit((string)str_replace(array(" ",":"),"",$value)) || !isset($time[0]) || !isset($time[1]) || $time[0] < 0 || $time[1] < 0 || $time[1] > 59)
			{
				throw new Exception("This attribute must be a valid time.\nName: <font color=#FF0000>".$name."</font>\nValue: <font color=#FF0000>".$value."</font>");
			}
			else
			{
				$this->$name = $value;
				return true;
			}
		}
	}

?>
